<?php
/*
	Copyright (C) 2008 - 2012 Inanta Martsanto
	Inanta Martsanto (inanta@inationsoft.com)

	This file is part of NewStep Framework.

	NewStep Framework is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	NewStep Framework is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with NewStep Framework.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Inationsoft\NS\Core;

use Inationsoft\NS\Database\ActiveRecord;
use Inationsoft\NS\Exception\IOException;

/**
 *Model base class
 *
 *@author Inanta Martsanto <inanta@inationsoft.com>
 */
abstract class Model extends ActiveRecord {
	static private $_modelsInstance = array();

	function getAll($columns = null, $condition = null, $order = null, $offset = null, $limit = null) {
		$this->findAll($columns, $condition, $order, $offset, $limit);
		return $this->toArray();
	}

	function get($columns = null, $condition = null) {
		$this->find($columns, $condition);
		return $this->toArray(1);
	}

	function getByPK($id) {
		$this->findByPK($id);
		return $this->toArray(1);
	}

	/**
	*Create or retrieve object instance
	*
	*/
	static function getInstance($model, $path = '') {
		if(isset(self::$_modelsInstance[$model]) && !self::$_modelsInstance[$model]->_isUsedInRelation) return self::$_modelsInstance[$model];
		if($path != '') $path .= '/';

		$path = NS_SYSTEM_PATH . '/' . Config::getInstance()->ApplicationFolder . '/models/' . $path . $model . '.php';

		if(!is_file($path)) throw new IOException(array('code' => IOException::FILE_NOT_FOUND, 'filename' => $path));
		if(!is_readable($path)) throw new IOException(array('code' => IOException::FILE_NOT_READABLE, 'filename' => $path));
		require_once($path);

		return (self::$_modelsInstance[$model] = new $model);
	}

	/**
	*Delete object instance
	*
	*/
	static function deleteInstance($model) {
		unset(self::$_modelsInstance[$model]);
	}
}
?>